package com.device.controller;

import com.device.entity.DeviceKey;
import com.device.service.DeviceKeyService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Api(tags = "Modbus配置管理")
@RestController
@RequestMapping("/api/device-keys")
@CrossOrigin(origins = "*")
public class DeviceKeyController {
    
    @Autowired
    private DeviceKeyService deviceKeyService;
    
    /**
     * 根据分设备ID获取Key表单列表
     */
    @ApiOperation(value = "获取Modbus配置列表", notes = "根据二级设备ID获取Modbus配置列表")
    @GetMapping("/sub-device/{subDeviceId}")
    public ResponseEntity<Map<String, Object>> getKeysBySubDeviceId(@PathVariable UUID subDeviceId) {
        Map<String, Object> response = new HashMap<>();
        try {
            List<DeviceKey> deviceKeys = deviceKeyService.getKeysBySubDeviceId(subDeviceId);// 根据分设备ID获取Key表单列表
            if(deviceKeys == null){
                response.put("success", false);
                response.put("message", "Key表单不存在");
                return ResponseEntity.notFound().build();
            }
            response.put("success", true);
            response.put("data", deviceKeys);
            response.put("message", "获取Modbus配置列表成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取Modbus配置列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据ID获取Key表单详情
     */
    @ApiOperation(value = "获取Modbus配置详情", notes = "根据ID获取Modbus配置详情")
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getKeyById(@PathVariable UUID id) {
        Map<String, Object> response = new HashMap<>();
        try {
            DeviceKey deviceKey = deviceKeyService.getKeyById(id);// 根据ID获取Key表单详情
            if (deviceKey != null) {
                response.put("success", true);
                response.put("data", deviceKey);
                response.put("message", "获取Key表单详情成功");
                return ResponseEntity.ok(response);
            } else {
                response.put("success", false);
                response.put("message", "Key表单不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取Key表单详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 创建Key表单
     */
    @ApiOperation(value = "创建Modbus配置", notes = "创建新的Modbus配置")
    @PostMapping
    public ResponseEntity<Map<String, Object>> createKey(@RequestBody DeviceKey deviceKey) {
        Map<String, Object> response = new HashMap<>();
        try {
            DeviceKey createdKey = deviceKeyService.createKey(deviceKey);
            response.put("success", true);
            response.put("data", createdKey);
            response.put("message", "创建Key表单成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "创建Key表单失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 更新Key表单
     */
    @ApiOperation(value = "更新Modbus配置", notes = "根据ID更新Modbus配置")
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateKey(@PathVariable UUID id, @RequestBody DeviceKey deviceKey) {
        Map<String, Object> response = new HashMap<>();
        try {
            DeviceKey updatedKey = deviceKeyService.updateKey(id, deviceKey);
            response.put("success", true);
            response.put("data", updatedKey);
            response.put("message", "更新Key表单成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "更新Key表单失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 删除Key表单
     */
    @ApiOperation(value = "删除Modbus配置", notes = "根据ID删除Modbus配置")
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteKey(@PathVariable UUID id) {
        Map<String, Object> response = new HashMap<>();
        try {
            deviceKeyService.deleteKey(id);
            response.put("success", true);
            response.put("message", "删除Key表单成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "删除Key表单失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 批量删除Key表单
     */
    @ApiOperation(value = "批量删除Modbus配置", notes = "根据ID列表批量删除Modbus配置")
    @DeleteMapping("/batch")
    public ResponseEntity<Map<String, Object>> deleteKeys(@RequestBody List<UUID> ids) {
        Map<String, Object> response = new HashMap<>();
        try {
            deviceKeyService.deleteKeys(ids);
            response.put("success", true);
            response.put("message", "批量删除Key表单成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "批量删除Key表单失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 检查Key编号在同一分设备下是否存在
     */
    @ApiOperation(value = "检查Key编号在同一分设备下是否存在", notes = "根据分设备ID和Key编号检查Key编号是否存在")
    @GetMapping("/exists/{subDeviceId}/{keyNumber}")
    public ResponseEntity<Map<String, Object>> checkKeyNumberExists(@PathVariable UUID subDeviceId, @PathVariable Integer keyNumber) {
        Map<String, Object> response = new HashMap<>();
        try {
            boolean exists = deviceKeyService.existsBySubDeviceIdAndKeyNumber(subDeviceId, keyNumber);
            response.put("success", true);
            response.put("exists", exists);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "检查Key编号失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 获取所有Key表单
     */
    @ApiOperation(value = "获取Modbus配置列表", notes = "根据二级设备ID获取Modbus配置列表")
    @GetMapping
    public ResponseEntity<Map<String, Object>> getAllKeys() {
        Map<String, Object> response = new HashMap<>();
        try {
            List<DeviceKey> deviceKeys = deviceKeyService.getAllKeys();
            response.put("success", true);
            response.put("data", deviceKeys);
            response.put("message", "获取所有Key表单成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "获取所有Key表单失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
    
    /**
     * 根据分设备ID统计Key表单数量
     */
    @ApiOperation(value = "根据分设备ID统计Key表单数量", notes = "根据分设备ID统计Key表单数量")
    @GetMapping("/count/{subDeviceId}")
    public ResponseEntity<Map<String, Object>> countBySubDeviceId(@PathVariable UUID subDeviceId) {
        Map<String, Object> response = new HashMap<>();
        try {
            int count = deviceKeyService.countBySubDeviceId(subDeviceId);
            response.put("success", true);
            response.put("count", count);
            response.put("message", "统计Key表单数量成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "统计Key表单数量失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);
        }
    }
}